from django.db import models

from courses.models import Course
from utils.models import BaseModel


class Order(BaseModel):
    ORDER_STATUS = (
        (1, "已支付"),
        (2, "取消"),
        (3, "超时取消"),
        (0, "未支付"),

    )

    PAY_METHOD = (
        (1, "支付宝"),
        (2, "微信"),

    )
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总价")
    real_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="实付价格")
    order_status = models.IntegerField(verbose_name="订单状态", default=0, choices=ORDER_STATUS)
    order_number = models.CharField(max_length=255, verbose_name="订单编号", unique=True)
    pay_method = models.IntegerField(verbose_name="支付方式", default=1, choices=PAY_METHOD)
    use_coupon = models.BooleanField(verbose_name="是否使用优惠券", default=False)
    use_coupon_id = models.IntegerField(verbose_name="使用的优惠券ID", null=True, blank=True)
    order_desc = models.CharField(max_length=500, verbose_name="订单描述")
    order_time = models.DateTimeField(verbose_name="下单时间", auto_now_add=True)
    pay_time = models.DateTimeField(verbose_name="支付时间", null=True, blank=True)
    trade_no = models.CharField(max_length=255, verbose_name="支付流水号", null=True, blank=True)
    user = models.ForeignKey("users.User", on_delete=models.DO_NOTHING, verbose_name="用户")

    class Meta:
        db_table = "tb_order"
        verbose_name = "订单"
        verbose_name_plural = verbose_name


class OrderDetail(BaseModel):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name="订单", related_name="order_details")
    course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, verbose_name="课程")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="课程价格")
    expire_days = models.IntegerField(verbose_name="有效周期(天)")
    expire_text = models.CharField(max_length=255, verbose_name="有效周期描述")
    expire_time = models.DateTimeField(verbose_name="到期时间", null=True, blank=True)
    order_number = models.CharField(max_length=255, verbose_name="订单编号")

    class Meta:
        db_table = "tb_order_detail"
        verbose_name = "订单详情"
        verbose_name_plural = verbose_name

    # def save(self, *args, **kwargs):
    #     #保存时自动填充order_number
    #     if not self.order_number and self.order:
    #         self.order_number = self.order.order_number
    #
    #     super().save(*args, **kwargs)
